<template>
  <div class="product-detail">
    <!-- 加载中状态 -->
    <el-skeleton :loading="loading" animated>
      <template #template>
        <div style="padding: 20px">
          <el-skeleton-item variant="image" style="width: 100%; height: 400px" />
          <div style="padding: 20px">
            <el-skeleton-item variant="h1" style="width: 50%" />
            <el-skeleton-item variant="text" style="width: 100%; margin-top: 16px" />
            <el-skeleton-item variant="text" style="width: 100%; margin-top: 16px" />
            <el-skeleton-item variant="text" style="width: 100%; margin-top: 16px" />
          </div>
        </div>
      </template>
      
      <!-- 实际内容 -->
      <template #default>
        <el-row :gutter="40">
          <el-col :span="12">
            <el-carousel height="400px">
              <el-carousel-item v-for="item in product.images" :key="item">
                <img :src="item" class="product-image">
              </el-carousel-item>
            </el-carousel>
          </el-col>
          
          <el-col :span="12">
            <div class="product-info">
              <h1>{{ product.name }}</h1>
              
              <div class="price-section">
                <div class="current-price">
                  <span class="label">团购价</span>
                  <span class="price">¥{{ product.price }}</span>
                  <span class="original-price">原价: ¥{{ product.originalPrice }}</span>
                </div>
              </div>
              
              <div class="group-info">
                <el-progress
                  :percentage="(product.groupCount / product.targetCount) * 100"
                  :format="format"
                  class="progress"
                />
                <div class="group-stats">
                  <span>已参团{{ product.groupCount }}人</span>
                  <span>目标{{ product.targetCount }}人</span>
                  <span>剩余{{ product.stock }}件</span>
                </div>
              </div>
              
              <div class="time-info">
                <span class="label">活动截止时间</span>
                <el-countdown :value="product.endTime" format="DD 天 HH:mm:ss" />
              </div>
              
              <div class="quantity-section">
                <span class="label">购买数量</span>
                <el-input-number
                  v-model="quantity"
                  :min="1"
                  :max="product.stock"
                  @change="handleQuantityChange"
                />
              </div>
              
              <div class="action-section">
                <el-button type="primary" size="large" @click="handleBuyNow" :disabled="product.stock <= 0">立即购买</el-button>
                <el-button size="large" @click="handleAddToCart" :disabled="product.stock <= 0">加入购物车</el-button>
              </div>
              
              <!-- 添加库存不足提示 -->
              <div v-if="product.stock <= 0" class="stock-warning">
                商品库存不足，暂时无法购买
              </div>
            </div>
          </el-col>
        </el-row>
        
        <div class="detail-section">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="商品详情" name="detail">
              <div class="detail-content" v-html="product.detail"></div>
            </el-tab-pane>
            <el-tab-pane label="团购规则" name="rules">
              <div class="rules-content">
                <h3>团购规则</h3>
                <p>{{ product.groupRules || '暂无团购规则' }}</p>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
    </el-skeleton>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const quantity = ref(1)
const activeTab = ref('detail')
const loading = ref(true) // 添加loading状态变量

// 初始化商品对象（使用模拟数据作为默认值）
const product = ref({
  id: route.params.id,
  name: '加载中...',
  price: 0,
  originalPrice: 0, // API中没有，我们会用price * 1.2计算
  images: ['https://via.placeholder.com/800x400'], // API只有一个image
  groupCount: 0, // API中没有，使用模拟值
  targetCount: 100, // API中没有，使用模拟值
  stock: 0,
  endTime: Date.now() + 1000 * 60 * 60 * 24 * 3, // API中没有，使用模拟值
  detail: '<p>加载中...</p>', // API中没有，使用description
  groupRules: '加载中...', // API中没有，使用模拟值
})

// 获取商品详情API
const fetchProductDetail = async () => {
  try {
    loading.value = true
    console.log('正在获取商品ID:', route.params.id)
    // 调用后端API
    const response = await fetch(`/api/products/${route.params.id}`)
    
    if (!response.ok) {
      throw new Error('获取商品详情失败')
    }
    
    const data = await response.json()
    console.log('API响应:', data)
    
    if (data.code === 200 && data.data) {
      // 成功获取数据，适配API返回的数据结构
      product.value = {
        ...product.value, // 保留默认值
        // 使用API返回的数据
        id: data.data.id,
        name: data.data.name,
        price: data.data.price,
        stock: data.data.stock,
        // 转换和适配字段
        originalPrice: data.data.price * 1.2, // 原价设为当前价格的1.2倍
        images: [data.data.image], // 转换单个图片为数组
        detail: data.data.description || '<p>暂无详情</p>', // 使用description作为详情
        // 保留模拟数据的字段
        groupCount: 30, // 模拟数据
        targetCount: 100, // 模拟数据
        endTime: Date.now() + 1000 * 60 * 60 * 24 * 3, // 3天后
        groupRules: '1. 达到目标人数后发货\n2. 未达到目标人数将自动退款\n3. 每人限购5件',
      }
      console.log('处理后的商品数据:', product.value)
    }
  } catch (error) {
    console.error('获取商品详情错误:', error)
    ElMessage.error('获取商品详情失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

const format = (percentage) => {
  return `${percentage}%`
}

const handleQuantityChange = (value) => {
  quantity.value = value
}

const handleBuyNow = () => {
  // TODO: 实现立即购买逻辑
  router.push('/cart')
}

const handleAddToCart = () => {
  // TODO: 实现加入购物车逻辑
  ElMessage.success('已加入购物车')
}

// 页面加载时获取商品详情
onMounted(() => {
  fetchProductDetail()
})
</script>

<style scoped>
.product-detail {
  padding: 20px;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  padding: 20px;
}

.product-info h1 {
  margin: 0 0 20px 0;
  font-size: 24px;
  color: #333;
}

.price-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.current-price {
  display: flex;
  align-items: baseline;
}

.label {
  font-size: 14px;
  color: #666;
  margin-right: 10px;
}

.price {
  font-size: 28px;
  color: #f56c6c;
  font-weight: bold;
  margin-right: 10px;
}

.original-price {
  color: #999;
  text-decoration: line-through;
}

.group-info {
  margin-bottom: 20px;
}

.progress {
  margin-bottom: 10px;
}

.group-stats {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 14px;
}

.time-info {
  margin-bottom: 20px;
}

.quantity-section {
  margin-bottom: 20px;
}

.action-section {
  display: flex;
  gap: 20px;
}

.detail-section {
  margin-top: 40px;
}

.detail-content, .rules-content {
  padding: 20px;
}

.rules-content h3 {
  margin-top: 0;
}

.stock-warning {
  margin-top: 15px;
  color: #f56c6c;
  font-size: 14px;
  background-color: #fef0f0;
  padding: 10px;
  border-radius: 4px;
}
</style> 